package com.javacoo.xservice.base;

import java.io.Serializable;
import java.util.Map;
import java.util.Optional;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;

import com.javacoo.xservice.base.utils.WebUtil;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.web.multipart.MultipartFile;

/**
 * 公共请求参数
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年5月12日上午9:25:09
 */
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseRequest implements Serializable{
	private static final long serialVersionUID = 1L;
	/**来源*/
	private static final String SOURCE = "source";
	/**appkey*/
	private static final String APP_KEY = "appKey";
	/**随机数KEY*/
	private static final String NONCE_KEY = "nonce";
	/**
	 * 来源
	 */
	private String source;
	/**
	 * appKey
	 */
    @NotBlank(message ="接入平台appKey(渠道号)不能为空")
    @Length(max = 16, message = "接入平台appKey(渠道号)超长")
	private String appKey;
	/**
	 * 请求时间戳
	 */
	@NotNull(message ="请求时间戳不能为空")
	private Long timestamp;
	/**
	 * 交易流水号
	 */
    @NotBlank(message = "交易流水号transactionSn不能为空")
    @Length(max = 32, message = "交易流水号超长")
	private String transactionSn;
	/**
	 * 随机数
	 */
	private String nonce;
    /**
     * 签名
     */
    private String sign;
	/**
	 * 请求方法
	 */
	private String method;
	/**
	 * 业务JSON参数
	 */
	@Valid
	private Object parameter;
	/**
	 * url查询参数
	 */
	private String queryString;
	/**
	 * url查询参数Map
	 */
	private Map<String, String> queryStringMap;
	/**
	 * 业务JSON参数Map
	 */
	private Map<String, String> parameterMap;

	/**
	 * 文件对象
	 */
	private Map<String, MultipartFile> files;
	
	public String getSource() {
		if(StringUtils.isBlank(source)){
			source = getQueryStringMap().get(SOURCE);
		}
		return source;
	}
	
	public String getAppKey() {
		if(StringUtils.isBlank(appKey)){
			appKey = getQueryStringMap().get(APP_KEY);
		}
		return appKey;
	}

	public Optional<Object> getParameter() {
		return Optional.ofNullable(parameter);
	}

	public String getNonce() {
		if(StringUtils.isBlank(nonce)){
			nonce = getQueryStringMap().get(NONCE_KEY);
		}
		return nonce;
	}

	public Map<String,String> getQueryStringMap() {
		if(null == queryStringMap){
			queryStringMap = WebUtil.getUrlMap(getQueryString());
		}
		return queryStringMap;
	}

	public Map<String, String> getParameterMap() {
		if(null == parameterMap){
			parameterMap = WebUtil.getObjectMap(parameter);
		}
		return parameterMap;
	}
}
